<?php

namespace common\models\c2\entity;

use backend\models\c2\entity\rbac\BeUser;
use cza\base\models\statics\EntityModelStatus;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\db\StaleObjectException;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%product}}".
 *
 * @property string $id
 * @property integer $type
 * @property string $seo_code
 * @property string $sku
 * @property string $name
 * @property string $label
 * @property string $value
 * @property string $low_price
 * @property string $sales_price
 * @property string $cost_price
 * @property string $market_price
 * @property string $supplier_id
 * @property string $currency_id
 * @property string $measure_id
 * @property string $warehouse_id
 * @property string $summary
 * @property string $description
 * @property integer $sold_count
 * @property integer $is_released
 * @property string $released_at
 * @property string $stock
 * @property string $created_by
 * @property string $updated_by
 * @property integer $status
 * @property integer $position
 * @property string $created_at
 * @property string $updated_at
 */
class Product extends \cza\base\models\ActiveRecord
{
    // public $warehouse_id;

    public $category_ids;

    use \common\traits\AttachmentTrait;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['low_price', 'sales_price', 'cost_price', 'market_price'], 'number'],
            [['supplier_id', 'currency_id', 'measure_id', 'sold_count', 'warehouse_id', 'created_by', 'updated_by', 'position'], 'integer'],
            [['summary', 'description'], 'string'],
            [['released_at', 'created_at', 'updated_at', 'category_ids'], 'safe'],
            [['type', 'is_released', 'status'], 'integer', 'max' => 4],
            [['seo_code', 'sku', 'name', 'label', 'value'], 'string', 'max' => 255],
            [['sku', 'name',], 'required',],
            // [['sku',], 'unique',],
            [['stock',], 'double',],
        ];
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            BlameableBehavior::className(),
            \yii\behaviors\BlameableBehavior::className(), // record created_by and updated_by
            'categoryBehavior' => [
                'class' => \yii2tech\ar\linkmany\LinkManyBehavior::className(),
                'relation' => 'categories', // relation, which will be handled
                'relationReferenceAttribute' => 'save_category_ids', // virtual attribute, which is used for related records specification
                'extraColumns' => [
                    'created_at' => function () {
                        return date('Y-m-d H:i:s');
                    },
                    'updated_at' => function () {
                        return date('Y-m-d H:i:s');
                    },
                ],
            ],
            'attachmentsBehavior' => [
                'class' => \cza\base\modules\Attachments\behaviors\AttachmentBehavior::className(),
                'attributesDefinition' => [
                    'avatar' => [
                        'class' => \common\models\c2\entity\EntityAttachmentImage::className(),
                        'validator' => 'image',
                        'rules' => [
                            'maxFiles' => 1,
                            'uploadRequired' => Yii::t('app.c2', 'Photo must upload.'),
                            // 'skipOnEmpty' => false,
                            // 'skipOnError' => false,
                            'extensions' => Yii::$app->params['config']['upload']['imageWhiteExts'],
                            // 'extensions' => ['jpg'],
                            'maxSize' => Yii::$app->params['config']['upload']['maxFileSize'],
                            // 'maxSize' => '2048',
                        ]
                    ]
                ]
            ],
        ]); // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'type' => Yii::t('app.c2', 'Type'),
            'seo_code' => Yii::t('app.c2', 'Seo Code'),
            'sku' => Yii::t('app.c2', 'Sku'),
            'name' => Yii::t('app.c2', 'Name'),
            'label' => Yii::t('app.c2', 'Label'),
            'value' => Yii::t('app.c2', 'Value'),
            'low_price' => Yii::t('app.c2', 'Low Price'),
            'sales_price' => Yii::t('app.c2', 'Sales Price'),
            'cost_price' => Yii::t('app.c2', 'Cost Price'),
            'market_price' => Yii::t('app.c2', 'Market Price'),
            'supplier_id' => Yii::t('app.c2', 'Supplier ID'),
            'currency_id' => Yii::t('app.c2', 'Currency ID'),
            'measure_id' => Yii::t('app.c2', 'Measure ID'),
            'summary' => Yii::t('app.c2', 'Summary'),
            'description' => Yii::t('app.c2', 'Description'),
            'sold_count' => Yii::t('app.c2', 'Sold Count'),
            'is_released' => Yii::t('app.c2', 'Is Released'),
            'released_at' => Yii::t('app.c2', 'Released At'),
            'created_by' => Yii::t('app.c2', 'Created By'),
            'updated_by' => Yii::t('app.c2', 'Updated By'),
            'status' => Yii::t('app.c2', 'Status'),
            'position' => Yii::t('app.c2', 'Position'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
            'warehouse_id' => Yii::t('app.c2', 'Warehouse'),
            'category_ids' => Yii::t('app.c2', 'Category Ids'),
            'stock' => Yii::t('app.c2', 'Stock'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\ProductQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\ProductQuery(get_called_class());
    }

    /**
     * setup default values
     **/
    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet);
    }

    public function getCreator()
    {
        return $this->hasOne(BeUser::className(), ['id' => 'created_by']);
    }


    public function getUpdator()
    {
        return $this->hasOne(BeUser::className(), ['id' => 'updated_by']);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        // if ($insert) {
        //     $model = new ProductStock();
        //     $model->warehouse_id = $this->warehouse_id;
        //     $model->product_id = $this->id;
        //     $model->save();
        // }
    }

    public function getStock()
    {
        return $this->hasOne(ProductStock::className(), ['product_id' => 'id']);
    }

    public function loadWarehouse()
    {
        if (!$this->isNewRecord) {
            $this->warehouse_id = $this->stock->warehouse_id;
        }
    }

    public function getCombinations()
    {
        return $this->hasMany(ProductCombination::className(), ['product_id' => 'id']);
    }

    public function getPackages()
    {
        return $this->hasMany(ProductPackage::className(), ['product_id' => 'id']);
    }

    public function beforeDelete()
    {
        // try {
        //     $this->getStock()->one()->delete();
        // } catch (StaleObjectException $e) {
        // } catch (\Throwable $e) {
        // }
        foreach ($this->getCombinations()->all() as $item) {
            try {
                $item->delete();
            } catch (StaleObjectException $e) {
            } catch (\Throwable $e) {
            }
        }
        foreach ($this->getPackages()->all() as $item) {
            try {
                $item->delete();
            } catch (StaleObjectException $e) {
            } catch (\Throwable $e) {
            }
        }
        return parent::beforeDelete(); // TODO: Change the autogenerated stub
    }

    public static function getMixedHashMap($keyField, $valField, $condition = '')
    {
        $models = self::find()->where($condition)->all();
        $data = ['' => Yii::t("app.c2", "Select options ..")];
        foreach ($models as $model) {
            $data[$model->id] = $model->sku . '(' . $model->name . ')';
        }
        return $data;
    }

    public function getCombinationOptionList($key = 'id', $val = 'name')
    {
        // foreach ($this->activeProductPackage as $item) {
        //     $options[$item->id] = $item->name;
        // }
        $options = ArrayHelper::map($this->getCombinations()->all(), $key, $val);
        return $options;
    }

    public function getPackageOptionList($key = 'id', $val = 'name')
    {
        // foreach ($this->activeProductPackage as $item) {
        //     $options[$item->id] = $item->name;
        // }
        $options = ArrayHelper::map($this->getPackages()->all(), $key, $val);
        return $options;
    }

    /**
     * return a format data array for select2 ajax response
     * @param type $keyField
     * @param type $valField
     * @param type $condition
     * @return array
     */
    public static function getOptionsListCallable($keyField, $valField, $condition = '', $params = [])
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return parent::getOptionsListCallable($keyField, $valField, $condition, $params); // TODO: Change the autogenerated stub
    }

    public function getMeasure()
    {
        return $this->hasOne(Measure::className(), ['id' => 'measure_id']);
    }

    public function getCategories()
    {
        return $this->hasMany(ProductCategory::className(), ['id' => 'category_id'])
            ->where(['status' => EntityModelStatus::STATUS_ACTIVE])
            ->viaTable('{{%product_category_rs}}', ['product_id' => 'id']);
    }

    public function loadCategoryIds()
    {
        $this->category_ids = implode(',', $this->getCategories()->select('id')->column());
    }

    public function beforeSave($insert)
    {
        // convert to array and save by link behavior
        $this->save_category_ids = !empty($this->category_ids) ? explode(',', $this->category_ids) : [];
        return parent::beforeSave($insert);
    }

    public function updateStock($num)
    {
        $this->updateAttributes([
            'stock' => $this->stock + $num,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }
}
